import { Router } from "express";
import multer from "multer";
import sharp from "sharp";
import { userDb } from "./auth";
import * as fs from "fs";
import * as path from "path";

const router = Router();

// 配置multer用于文件上传
const upload = multer({
  storage: multer.memoryStorage(),
  limits: {
    fileSize: 5 * 1024 * 1024, // 5MB限制
  },
});

// 人脸数据存储文件路径
const FACE_DB_PATH = path.join(process.cwd(), "face_data.json");

// 持久化人脸库
class PersistentFaceDb {
  private faceData: Map<string, { name: string; hash: string; timestamp: string }>;

  constructor() {
    this.faceData = new Map();
    this.loadFromFile();
  }

  // 从文件加载数据
  private loadFromFile() {
    try {
      if (fs.existsSync(FACE_DB_PATH)) {
        const fileContent = fs.readFileSync(FACE_DB_PATH, 'utf-8');
        const data = JSON.parse(fileContent);
        this.faceData = new Map(Object.entries(data));
        console.log(`[人脸数据库] 已加载 ${this.faceData.size} 个人脸记录`);
      } else {
        console.log("[人脸数据库] 数据文件不存在，创建新的数据库");
      }
    } catch (error) {
      console.error("[人脸数据库] 加载失败:", error);
      this.faceData = new Map();
    }
  }

  // 保存数据到文件
  private saveToFile() {
    try {
      const dataObject = Object.fromEntries(this.faceData);
      fs.writeFileSync(FACE_DB_PATH, JSON.stringify(dataObject, null, 2), 'utf-8');
      console.log(`[人脸数据库] 已保存 ${this.faceData.size} 个人脸记录到文件`);
    } catch (error) {
      console.error("[人脸数据库] 保存失败:", error);
    }
  }

  // 设置人脸数据
  set(personId: string, data: { name: string; hash: string }) {
    this.faceData.set(personId, {
      ...data,
      timestamp: new Date().toISOString()
    });
    this.saveToFile(); // 立即保存
  }

  // 获取人脸数据
  get(personId: string) {
    return this.faceData.get(personId);
  }

  // 检查是否存在
  has(personId: string): boolean {
    return this.faceData.has(personId);
  }

  // 删除人脸数据
  delete(personId: string): boolean {
    const result = this.faceData.delete(personId);
    if (result) {
      this.saveToFile(); // 立即保存
    }
    return result;
  }

  // 获取所有数据
  getAllEntries() {
    return Array.from(this.faceData.entries());
  }

  // 获取数据库大小
  get size(): number {
    return this.faceData.size;
  }
}

// 创建持久化人脸数据库实例
const faceDb = new PersistentFaceDb();

// 工具：计算均值哈希(aHash)，返回64位字符串
async function calcImageAHash(buffer: Buffer): Promise<string> {
  // 使用 sharp 生成 8x8 灰度图并读取像素
  const resized = await sharp(buffer).grayscale().resize(8, 8, { fit: "fill" }).raw().toBuffer();
  // resized 为 8*8 = 64 个字节（单通道）
  let sum = 0;
  for (let i = 0; i < resized.length; i++) sum += resized[i];
  const avg = sum / resized.length;
  let bits = "";
  for (let i = 0; i < resized.length; i++) bits += resized[i] >= avg ? "1" : "0";
  return bits;
}

function hammingDistance(a: string, b: string): number {
  let d = 0;
  const n = Math.min(a.length, b.length);
  for (let i = 0; i < n; i++) if (a[i] !== b[i]) d++;
  return d + Math.abs(a.length - b.length);
}

// 人脸检测（简单：只要能读取图像就认为检测到1张脸）
router.post("/detect", upload.single("image"), async (req, res) => {
  try {
    if (!req.file) return res.status(400).json({ success: false, error: "缺少图片(image)" });
    await sharp(req.file.buffer).metadata();
    res.json({ success: true, face_count: 1, faces: [], timestamp: new Date().toISOString() });
  } catch (error) {
    res.status(500).json({ success: false, message: "人脸检测失败" });
  }
});

// 人脸注册：字段 image 或 file，person_name，person_id（可选）
router.post("/register", upload.fields([{ name: "image", maxCount: 1 }, { name: "file", maxCount: 1 }]), async (req, res) => {
  try {
    const filesAny = req.files as any;
    const upload = filesAny?.image?.[0] || filesAny?.file?.[0];
    if (!upload) return res.status(400).json({ success: false, message: "缺少图片(image/file)" });
    const personName = req.body?.person_name || "unknown";
    const personId = req.body?.person_id || `${Date.now()}`;
    const hash = await calcImageAHash(upload.buffer);
    faceDb.set(personId, { name: personName, hash });
    
    // 更新用户数据库中的has_face状态
    let userUpdated = false;
    for (const [userId, user] of userDb.entries()) {
      if (user.username === personId || user.id === personId || userId === personId) {
        user.has_face = true;
        userDb.set(userId, user); // 确保更新保存
        userUpdated = true;
        console.log(`[人脸注册] 更新用户 ${user.username}(ID:${user.id}) 的人脸状态为 true`);
        break;
      }
    }
    
    // 添加注册调试日志
    console.log(`[人脸注册] 用户: ${personId} (${personName})`);
    console.log(`[人脸注册] 生成哈希: ${hash.substring(0, 16)}...`);
    console.log(`[人脸注册] 当前库中人脸数: ${faceDb.size}`);
    console.log(`[人脸注册] 用户状态更新: ${userUpdated ? '成功' : '用户不存在'}`);
    
    return res.json({ success: true, person_id: personId, person_name: personName, face_count: 1, quality_score: 0.8, timestamp: new Date().toISOString() });
  } catch (error: any) {
    console.error("/v1/face/register 错误:", error?.message || error);
    return res.status(500).json({ success: false, message: `人脸注册失败: ${error?.message || 'unknown'}` });
  }
});

// 人脸验证：字段 file 或 image，必带 user_id（作为库中的 person_id）
router.post("/verify", upload.fields([{ name: "file", maxCount: 1 }, { name: "image", maxCount: 1 }]), async (req, res) => {
  try {
    const upload = (req.files as any)?.file?.[0] || (req.files as any)?.image?.[0];
    const userId = req.body?.user_id;
    if (!upload) return res.status(400).json({ success: false, message: "未上传图片文件(file/image)" });
    if (!userId) return res.status(400).json({ success: false, message: "缺少 user_id" });

    const entry = faceDb.get(String(userId));
    if (!entry) {
      console.log(`[人脸验证] 用户 ${userId} 未找到人脸记录`);
      return res.status(200).json({ 
        success: false, 
        code: "NO_ENROLL", 
        message: "未找到该用户的人脸信息，请先完成人脸录入",
        need_enroll: true
      });
    }

    const probeHash = await calcImageAHash(upload.buffer);
    const dist = hammingDistance(entry.hash, probeHash);
    const similarity = 1 - dist / 64; // 0~1
    const passed = similarity >= 0.65; // 降低阈值，提高通过率
    
    // 添加调试日志
    console.log(`[人脸验证] 用户: ${userId}`);
    console.log(`[人脸验证] 注册哈希: ${entry.hash.substring(0, 16)}...`);
    console.log(`[人脸验证] 验证哈希: ${probeHash.substring(0, 16)}...`);
    console.log(`[人脸验证] 汉明距离: ${dist}/64`);
    console.log(`[人脸验证] 相似度: ${similarity.toFixed(3)} (阈值: 0.65)`);
    console.log(`[人脸验证] 结果: ${passed ? '通过' : '不通过'}`);
    
    // 始终返回 200，使前端拿到明确结果后停止转圈
    return res.status(200).json({ 
      success: passed, 
      code: passed ? "OK" : "NOT_MATCH", 
      message: passed ? "人脸验证通过" : `人脸不匹配 (相似度: ${similarity.toFixed(3)})，请更换角度或重新录入`,
      similarity: Number(similarity.toFixed(3)),
      debug: {
        distance: dist,
        threshold: 0.65,
        registered_hash: entry.hash.substring(0, 16) + "...",
        probe_hash: probeHash.substring(0, 16) + "..."
      }
    });
  } catch (error) {
    console.error("verify 错误", error);
    res.status(500).json({ success: false, message: "人脸验证失败" });
  }
});

// 检查用户是否已注册人脸
router.get("/check/:user_id", async (req, res) => {
  try {
    const userId = req.params.user_id;
    if (!userId) {
      return res.status(400).json({ 
        success: false, 
        message: "缺少用户ID" 
      });
    }

    const hasRegistered = faceDb.has(userId);
    const faceInfo = faceDb.get(userId);
    
    console.log(`[人脸状态检查] 用户: ${userId}, 已注册: ${hasRegistered}`);
    
    return res.json({
      success: true,
      has_face: hasRegistered,
      person_id: userId,
      person_name: faceInfo?.name || null,
      registered_at: faceInfo?.timestamp || null,
      timestamp: new Date().toISOString()
    });
  } catch (error: any) {
    console.error("/v1/face/check 错误:", error?.message || error);
    return res.status(500).json({ 
      success: false, 
      message: `检查失败: ${error?.message || 'unknown'}` 
    });
  }
});

// 获取所有已注册的人脸信息
router.get("/list", async (req, res) => {
  try {
    const allFaces = faceDb.getAllEntries();
    const faceList = allFaces.map(([personId, data]) => ({
      person_id: personId,
      person_name: data.name,
      registered_at: data.timestamp,
      quality_score: 0.8 // 默认质量分数
    }));

    console.log(`[人脸列表] 返回 ${faceList.length} 个人脸记录`);
    
    return res.json({
      success: true,
      faces: faceList,
      total_count: faceList.length,
      timestamp: new Date().toISOString()
    });
  } catch (error: any) {
    console.error("/v1/face/list 错误:", error?.message || error);
    return res.status(500).json({ 
      success: false, 
      message: `获取列表失败: ${error?.message || 'unknown'}` 
    });
  }
});

// 删除用户的人脸数据
router.delete("/delete/:user_id", async (req, res) => {
  try {
    const userId = req.params.user_id;
    if (!userId) {
      return res.status(400).json({ 
        success: false, 
        message: "缺少用户ID" 
      });
    }

    const existed = faceDb.has(userId);
    if (!existed) {
      return res.status(404).json({
        success: false,
        message: "未找到该用户的人脸数据"
      });
    }

    const deleted = faceDb.delete(userId);
    
    // 同时更新用户数据库中的状态
    for (const [userKey, user] of userDb.entries()) {
      if (user.username === userId || user.id === userId || userKey === userId) {
        user.has_face = false;
        userDb.set(userKey, user); // 确保更新保存
        console.log(`[人脸删除] 更新用户 ${user.username}(ID:${user.id}) 的人脸状态为 false`);
        break;
      }
    }

    console.log(`[人脸删除] 用户: ${userId}, 删除成功: ${deleted}`);
    
    return res.json({
      success: true,
      message: "人脸数据删除成功",
      person_id: userId,
      timestamp: new Date().toISOString()
    });
  } catch (error: any) {
    console.error("/v1/face/delete 错误:", error?.message || error);
    return res.status(500).json({ 
      success: false, 
      message: `删除失败: ${error?.message || 'unknown'}` 
    });
  }
});

// 活体检测序列：这里只做动作顺序校验与简单通过
router.post("/liveness_sequence_check", upload.single("image"), async (req, res) => {
  try {
    const { session_id, action } = req.body || {};
    if (!session_id || !action) return res.status(400).json({ success: false, message: "缺少参数" });
    // 简化：收到图片就当该动作通过；由前端控制动作顺序
    const done = false;
    return res.json({ success: true, is_live: true, done, message: "动作通过" });
  } catch (error) {
    res.status(500).json({ success: false, message: "活体检测失败" });
  }
});

// 同步用户人脸状态（管理功能）
router.post("/sync-status", async (req, res) => {
  try {
    let syncCount = 0;
    
    // 重置所有用户的人脸状态为false
    for (const [userKey, user] of userDb.entries()) {
      user.has_face = false;
      userDb.set(userKey, user);
    }
    
    // 根据人脸库重新设置状态
    for (const [personId] of faceDb.getAllEntries()) {
      for (const [userKey, user] of userDb.entries()) {
        if (user.username === personId || user.id === personId || userKey === personId) {
          user.has_face = true;
          userDb.set(userKey, user);
          syncCount++;
          console.log(`[状态同步] 用户 ${user.username} 人脸状态已同步`);
          break;
        }
      }
    }
    
    console.log(`[状态同步] 完成，同步了 ${syncCount} 个用户的人脸状态`);
    
    return res.json({
      success: true,
      message: `人脸状态同步完成，共同步 ${syncCount} 个用户`,
      synced_count: syncCount,
      face_count: faceDb.size,
      timestamp: new Date().toISOString()
    });
  } catch (error: any) {
    console.error("/v1/face/sync-status 错误:", error?.message || error);
    return res.status(500).json({ 
      success: false, 
      message: `状态同步失败: ${error?.message || 'unknown'}` 
    });
  }
});

// 健康检查
router.get("/health", async (_req, res) => {
  res.json({ service: "face", status: "healthy", face_count: faceDb.size, timestamp: new Date().toISOString() });
});

export default router;
